/*
 *   Copyright (c) 2010-2022, SIUFUNG
 */
package net.siufung.market.base.dict.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.siufung.core.model.enums.DeletedEnum;
import net.siufung.core.page.PagerResult;
import net.siufung.core.result.Result;
import net.siufung.core.result.ResultFail;
import net.siufung.core.result.ResultOk;
import net.siufung.core.utils.CopyUtil;
import net.siufung.market.base.dict.controller.assembler.DictAssembler;
import net.siufung.market.base.dict.controller.model.dict.DictDto;
import net.siufung.market.base.dict.controller.model.dict.DictSaveDto;
import net.siufung.market.base.dict.controller.model.dict.DictUpdateDto;
import net.siufung.market.base.dict.controller.model.dict.DictPageDto;
import net.siufung.market.base.dict.controller.model.dict.DictVo;
import net.siufung.market.base.dict.controller.regulation.DictRegulation;
import net.siufung.market.base.dict.mapper.IDictMapper;
import net.siufung.market.base.dict.mapper.IDictTypeMapper;
import net.siufung.market.base.dict.mapper.entity.Dict;
import net.siufung.market.base.dict.mapper.entity.DictType;
import net.siufung.market.base.dict.service.IDictService;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 字典数据 前端控制器
 *
 * @author 陈建峰
 * @since 2022-07-08 15:30:15
 */
@Api(tags = "字典数据")
@Slf4j
@AllArgsConstructor
@RestController
@RequestMapping("/data/dict")
public class DictController {

    private final IDictMapper dictMapper;
    private final IDictService dictService;
    private final IDictTypeMapper dictTypeMapper;

    /**
     * 通过主键获取 字典数据
     * @param id 主键
     * @return Result<DictVo>
     * */
    @ApiOperation(value = "通过Id获取字典数据信息")
    @GetMapping(value = "/id/{id}")
    public Result<DictVo> getById(
            @PathVariable("id") Integer id) {
        return Result.ok(
            DictAssembler.from(dictMapper.selectById(id)));
    }

    /**
     * 获取 字典数据列表
     * @param dictDto 属性
     * @return Result<List<DictVo>>
     * */
    @ApiOperation(value = "获取字典数据列表")
    @PostMapping(value = "/list")
    public Result<List<DictVo>> list(
            @RequestBody DictDto dictDto) {
        return Result.ok(
            DictAssembler.fromList(
                    dictMapper.selectList(Wrappers.query(dictDto.to()))));
    }

    /**
     * 获取 字典数据分页
     * @param dictPageDto 属性
     * @return 查询分页结果
     * */
    @ApiOperation(value = "获取字典数据分页")
    @PostMapping(value="/page")
    public Result<PagerResult<DictVo>> getPage(
            @RequestBody DictPageDto dictPageDto) {
        dictPageDto.validated();
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(!Strings.isNullOrEmpty(dictPageDto.getDictCode()),
                Dict::getDictCode, dictPageDto.getDictCode());
        wrapper.lambda().eq(Objects.nonNull(dictPageDto.getDictTypeId()),
                Dict::getDictTypeId, dictPageDto.getDictTypeId());
        wrapper.lambda().orderByDesc(Dict::getCreatedAt);
        IPage<Dict> dictPage = dictMapper.selectPage(
                new Page<>(dictPageDto.getPageNo(), dictPageDto.getPageSize()), wrapper);
        List<Dict> dictList = dictPage.getRecords();
        PagerResult<DictVo> dictVoPage = new PagerResult<>(
                dictPage.getCurrent(), dictPage.getSize(), dictPage.getTotal());
        List<Integer> dictTypeIdList = dictList.stream()
                .map(Dict::getDictTypeId).distinct().collect(Collectors.toList());
        List<DictType> dictTypeList = Lists.newArrayList();
        if (!CollectionUtils.isEmpty(dictTypeIdList)) {
            dictTypeList = dictTypeMapper.selectList(
                    new LambdaQueryWrapper<DictType>().in(DictType::getId, dictTypeIdList));
        }
        dictVoPage.setRecords(
            DictAssembler.fromList(dictList, dictTypeList));
        return Result.ok(dictVoPage);
    }

    /**
     * 通过主键删除 字典数据 对象
     * @param id 主键
     * @return 删除结果
     * */
    @ApiOperation(value = "删除字典数据对象")
    @PostMapping(value="/delete/{id}")
    public Result<Void> deleteById(
        @PathVariable("id") Integer id) {
        DictRegulation.Remove dictDeleteRegulation = new DictRegulation.Remove(dictMapper);
        dictDeleteRegulation.isSatisfiedBy(id);
        if(dictService.removeById(id)){
            return Result.ok(ResultOk.REMOVE);
        }
        return Result.fail(ResultFail.DATA_REMOVE_ERROR);
    }

    /**
     * 创建 字典数据
     * @param dictSaveDto 对象属性
     * @return 创建结果
     * */
    @ApiOperation(value = "创建 字典数据")
    @PostMapping(value="/create")
    public Result<Void> create(
            @RequestBody DictSaveDto dictSaveDto) {
        dictSaveDto.validated();
        DictRegulation.Save dictCreateRegulation = new DictRegulation.Save(dictMapper);
        dictCreateRegulation.isSatisfiedBy(dictSaveDto);
        if(dictService.save(dictSaveDto.to())){
            return Result.ok(ResultOk.ADD);
        }
        return Result.fail(ResultFail.DATA_ADD_ERROR);
    }

    /**
     * 更新 字典数据
     * @param dictUpdateDto 对象属性
     * @return Result<Void>
     * */
    @ApiOperation(value = "更新 字典数据 信息")
    @PostMapping(value="/updateById")
    public Result<Void> updateById(
            @RequestBody DictUpdateDto dictUpdateDto) {
        dictUpdateDto.validated();
        DictRegulation.Update updateRegulation = new DictRegulation.Update(dictMapper);
        updateRegulation.isSatisfiedBy(dictUpdateDto);
        Dict dictOf = dictService.getById(dictUpdateDto.getId());
        CopyUtil.copyPropertiesIgnoreNull(dictUpdateDto.to(), dictOf);
        if(dictService.updateById(dictOf)){
            return Result.ok(ResultOk.UPDATE);
        }
        return Result.fail(ResultFail.DATA_UPDATE_ERROR);
    }

    /**
     * 更新 字典数据 状态
     * @param id 主键
     * @param deleted 数据状态
     * @return Result<Void>
     * */
    @ApiOperation(value = "更新 字典数据 状态")
    @PostMapping(value="/status/{id}/{deleted}")
    public Result<Void> updateStatusById(
            @PathVariable("id") Integer id,
            @PathVariable("deleted") boolean deleted) {
        DictRegulation.Status dictStatusRegulation = new DictRegulation.Status(dictMapper);
        dictStatusRegulation.isSatisfiedBy(id);
        if(dictService.updateStatusById(id, DeletedEnum.get(deleted))){
            return Result.ok(ResultOk.STATUS);
        }
        return Result.fail(ResultFail.DATA_UPDATE_ERROR);
    }

}